package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.mapper.AddressBookMapper;
import com.itheima.reggie.service.AddressBookService;
import com.itheima.reggie.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 地址管理业务层接口实现类
 * @Author Vsunks.v
 * @Blog blog.sunxiaowei.net/996.mba
 * @Description: 地址管理业务层接口实现类。
 * 继承ServiceImpl类，实现AddressBookService接口
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Autowired
    AddressBookMapper addressBookMapper;

    /**
     * 设置默认收货地址
     * 每个用户可以有很多地址，但是默认地址只能有一个
     * 先将该用户所有地址的is_default更新为0 ， 然后将当前的设置的默认地址的is_default设置为1
     * @param addressBook
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setDefaultAddress(AddressBook addressBook) {

        // 获取当前登录的用户id
        Long userId = ThreadLocalUtil.getCurrentId();

        // 新建一个地址对象，设为非默认
        AddressBook newAb = new AddressBook();
        newAb.setIsDefault(0);

        // 该用户所有地址的is_default更新为0
        LambdaQueryWrapper<AddressBook> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(AddressBook::getUserId, userId);
        addressBookMapper.update(newAb, updateWrapper);

        // 设置指定地址为默认
        addressBook.setIsDefault(1);
        addressBookMapper.updateById(addressBook);

        return true;
    }
}
